﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TaoPortal.BusinessLogic.DTO;
using TaoPortal.BusinessLogic.Extensions;
using TaoPortal.DataAccess;
using TaoPortal.Entity;

namespace TaoPortal.BusinessLogic.Repository
{
    public class UserRepository : BaseRepository
    {
        public UserRepository(DataContext dbcontext)
        {
            db = dbcontext;
        }
        public UserRepository()
            : this(new DataContext())
        {

        }

        public PagedList<UserList> GetUserList(string userName, string roleId, string tel, string phone, string email, DateTime? startDate, DateTime? endDate, int pageIndex, int pageSize)
        {
            var temp = (from user in db.TP_Users
                        join uinfo in db.TP_UserInfo on user.UserInfoID equals uinfo.ID into userinfos
                        from userinfo in userinfos.DefaultIfEmpty()
                        join apiu in db.TP_APIUsers on user.ID equals apiu.UserID into apiusers
                        from apiuser in apiusers.DefaultIfEmpty()
                        orderby user.CreateTime descending
                        select new
                        {
                            APIUser = apiuser,
                            Status = user.Status,
                            CreateBy = user.CreateBy,
                            CreateTime = user.CreateTime,
                            Email = user.Email,
                            ID = user.ID,
                            Integral = user.Integral,
                            LastIP = user.LastIP,
                            LastLoginTime = user.LastLoginTime,
                            Name = user.Name,
                            Password = user.Password,
                            Role = (from r in db.TP_Role join ur in db.TP_UserRoles on r.ID equals ur.RoleID where ur.UserID == user.ID select r),
                            UpdateBy = user.UpdateBy,
                            UpdateTime = user.UpdateTime,
                            UserInfo = userinfo,
                            UserInfoID = user.UserInfoID,
                            UserName = user.UserName
                        });
            if (!string.IsNullOrEmpty(userName))
                temp = temp.Where(x => x.UserName == userName);
            if (startDate != null)
                temp = temp.Where(x => x.CreateTime >= startDate);
            if (endDate != null)
            {
                endDate = endDate.Value.AddDays(1);
                temp = temp.Where(x => x.CreateTime < endDate);
            }
            if (!string.IsNullOrEmpty(userName))
                temp = temp.Where(x => x.UserName == userName);
            if (!string.IsNullOrEmpty(tel))
                temp = temp.Where(x => x.UserInfo.Tel == tel);
            if (!string.IsNullOrEmpty(phone))
                temp = temp.Where(x => x.UserInfo.Phone == phone);
            if (!string.IsNullOrEmpty(email))
                temp = temp.Where(x => x.Email == email);
            if (!string.IsNullOrEmpty(roleId))
                temp = temp.Where(x => x.Role.Where(z => z.ID == roleId).Count() > 0);
            var d = temp.OrderByDescending(x => x.CreateTime).Select(x => new UserList
            {
                Status = x.Status,
                CreateBy = x.CreateBy,
                CreateTime = x.CreateTime,
                Email = x.Email,
                ID = x.ID,
                Integral = x.Integral,
                LastIP = x.LastIP,
                LastLoginTime = x.LastLoginTime,
                Name = x.Name,
                Password = x.Password,
                UpdateBy = x.UpdateBy,
                UpdateTime = x.UpdateTime,
                UserInfoID = x.UserInfoID,
                UserName = x.UserName
            }).ToPagedList(pageIndex, pageSize);
            return d;
        }

        public FullUserInfo GetUserByID(string id)
        {
            var u = (from user in db.TP_Users
                     join uinfo in db.TP_UserInfo on user.UserInfoID equals uinfo.ID
                     join apiu in db.TP_APIUsers on user.ID equals apiu.UserID
                     join rolerel in db.TP_UserRoles on user.ID equals rolerel.UserID
                     join role in db.TP_Role on rolerel.RoleID equals role.ID into roles
                     where user.ID == id
                     select new FullUserInfo
                     {
                         TP_APIUsers = apiu,
                         TP_Role = roles,
                         TP_UserInfo = uinfo,
                         TP_Users = user
                     }).FirstOrDefault();
            return u;
        }

        public void AddUser(TP_Users user, List<TP_UserRoles> userroles, TP_UserInfo userinfo, TP_APIUsers apiuser)
        {
            db.TP_Users.Add(user);
            foreach (var item in userroles)
            {
                db.TP_UserRoles.Add(item);
            }
            if (apiuser != null)
                db.TP_APIUsers.Add(apiuser);
            if (userinfo != null)
                db.TP_UserInfo.Add(userinfo);
            SaveChanges();
        }

        public void EditUser(TP_Users user, List<TP_UserRoles> userroles, TP_UserInfo userinfo)
        {
            var _user = db.TP_Users.Where(x => x.ID == user.ID).FirstOrDefault();
            if (_user != null)
            {
                _user.Email = user.Email;
                _user.UpdateBy = user.UpdateBy;
                _user.UpdateTime = user.UpdateTime;
                _user.Integral = user.Integral;
                _user.Password = user.Password;
                _user.Status = user.Status;
                _user.Name = user.Name;
            }
            if (!string.IsNullOrEmpty(user.UserInfoID))
            {
                var _userinfo = db.TP_UserInfo.Where(x => x.ID == user.UserInfoID).FirstOrDefault();
                if (_userinfo == null)
                {
                    db.TP_UserInfo.Add(userinfo);
                }
                else
                {
                    _userinfo.Address = userinfo.Address;
                    _userinfo.Answer = userinfo.Answer;
                    _userinfo.Birthday = userinfo.Birthday;
                    _userinfo.City = userinfo.City;
                    _userinfo.County = userinfo.County;
                    _userinfo.Gender = userinfo.Gender;
                    _userinfo.Introduction = userinfo.Introduction;
                    _userinfo.Phone = userinfo.Phone;
                    _userinfo.Photo = userinfo.Photo;
                    _userinfo.PostCode = userinfo.PostCode;
                    _userinfo.Province = userinfo.Province;
                    _userinfo.QQ = userinfo.QQ;
                    _userinfo.Question = userinfo.Question;
                    _userinfo.Tel = userinfo.Tel;
                    _userinfo.RealName = userinfo.RealName;
                    _userinfo.UpdateTime = userinfo.UpdateTime;
                    _userinfo.UpdateBy = userinfo.UpdateBy;
                }
            }
            var roles = db.TP_UserRoles.Where(x => x.UserID == user.ID).ToList();
            foreach (var item in roles)
            {
                db.TP_UserRoles.Remove(item);
            }
            foreach (var item in userroles)
            {
                db.TP_UserRoles.Add(item);
            }
            SaveChanges();
        }

        public void DisableUser(string id, string status)
        {
            var _user = db.TP_Users.Where(x => x.ID == id).FirstOrDefault();
            if (_user != null)
                _user.Status = status;
            SaveChanges();
        }


        public List<TP_Role> GetRoleList()
        {
            var d = (from r in db.TP_Role
                     select r).ToList();
            return d;
        }

        public List<TP_Role> GetAllRole()
        {
            var d = (from r in db.TP_Role
                     select r).ToList();
            return d;
        }

        public TP_Role GetRoleByID(string id)
        {
            return db.TP_Role.Where(x => x.ID == id).FirstOrDefault();
        }

        public int IfDeleteRole(string id)
        {
            int res = 0;
            if (db.TP_UserRoles.Where(x => x.RoleID == id).Count() > 0)
            {
                return 1;
            }
            if (db.TP_RoleRights.Where(x => x.RoleID == id).Count() > 0)
            {
                return 2;
            }
            else
            {
                db.DeleteEntity(new TP_Role { ID = id });
                SaveChanges();
            }
            return res;
        }

        public void AddRole(TP_Role role)
        {
            db.TP_Role.Add(role);
            SaveChanges();
        }

        public void EditRole(TP_Role role)
        {
            var _role = db.TP_Role.Where(x => x.ID == role.ID).FirstOrDefault();
            if (_role != null)
            {
                _role.Integral = role.Integral;
                _role.RoleDesc = role.RoleDesc;
                _role.RoleName = role.RoleName;
                _role.RoleType = role.RoleType;
                SaveChanges();
            }
        }

        public List<TP_Zone> GetProvince()
        {
            return db.TP_Zone.Where(x => x.ZoneLevel == "1").Select(x => x).ToList();
        }

        public List<TP_Zone> GetZoneByParentID(string id)
        {
            return db.TP_Zone.Where(x => x.ParentID == id).Select(x => x).ToList();
        }

    }
}
